package com.yifushidai.service;

import com.alibaba.fastjson.JSON;
import com.yifushidai.entity.ApiUniqueMac;
import com.yifushidai.entity.RoomManagementEntity;
import com.yifushidai.mapper.ApiUniqueMacMapper;
import com.yifushidai.mapper.RoomManagementEntityMapper;
import com.yifushidai.utils.ErrorCodeEnum;
import com.yifushidai.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoomManagementService {
    @Autowired
    private ApiUniqueMacMapper apiUniqueMacMapper;
    @Autowired
    private RoomManagementEntityMapper roomManagementEntityMapper;

    public R saveAfterDelete(String mac, String param) throws InterruptedException {
        List<RoomManagementEntity> list = JSON.parseArray(param, RoomManagementEntity.class);
        ApiUniqueMac one = apiUniqueMacMapper.selectOne(ApiUniqueMac.builder().mac(mac).build());
        if (null == one) return R.error(ErrorCodeEnum.MAC_NULL);
        roomManagementEntityMapper.delete(RoomManagementEntity.builder().uniqueMac(mac).build());

        double totalPower = 0;
        for (RoomManagementEntity p : list) {
            switch (p.getAttrKey()) {
                case "户型":
                    p.setPower(0.0);
                    p.setNumber(0);
                    break;
                case "空调管理":
                    p.setPower(0.9 * p.getAirP());
                    break;
                case "照明灯管理":
                    if ("射灯".equals(p.getAttrVal())) {
                        p.setPower(0.005);
                    } else {
                        p.setPower(0.035);
                    }
                    break;
                case "浴霸或风暖":
                case "地暖":
                case "取暖器":
                case "热水器":
                case "自定义":
                default:
                    break;
            }
            roomManagementEntityMapper.insertSelective(p);
            totalPower += p.getPower() * p.getNumber();
        }
//        roomManagementEntityMapper.insertList(list);

        //更新家电信息
        one.setPow(totalPower);
        return R.ok().put(apiUniqueMacMapper.updateByPrimaryKeySelective(one));
    }

    public R queryListByMac(String mac) {
        return R.ok().put(roomManagementEntityMapper.select(RoomManagementEntity.builder().uniqueMac(mac).build()));
    }
}
